import { activityApi } from '../../../api/activity'
import { $event, $utils } from '../../../utils'
import { GlobalData } from '../../../store/state'
import { getServer, isLogin } from '../../../store/mutations'
import { checkAuth } from '../../../store/actions'

Page({
  data: {
    activity: {} as Activity,
    /** 想加入锁 */
    wantJoin: false,
    comment: [] as DomoFeed[],
    isLoading: false,
    access: GlobalData.access,
    id: 0,
    isCreater: false,
    mineId: 0,
    events: {} as Activity,
    scrollTop: false,
    navigationHeight: GlobalData.navigationHeight,
  },
  async onLoad(query: any) {
    this.getPosition()
    let id = query.id
    if (!id && query.scene) {
      const scene = $utils.parseQueryString(query.scene)
      id = scene.id
    }
    this.setData({ id })
    // await this.getDetail(id)
    if (isLogin()) {
      await this.getComment(id)
      this.getUserId()
    } else {
      $event.on('after:login', this, async () => {
        await this.getComment(id)
      })
      $event.emit('login')
    }
    this.getBoot()
    $event.on('after:changeFeedList', this, async () => {
      await this.getComment(id)
      const tmp = this.data.activity
      tmp.comments_count = tmp.comments_count + 1
      this.setData({
        activity: tmp,
      })
    })
  },
  onShow() {
    this.getDetail(this.data.id)
    this.getComment(this.data.id)
  },
  onPageScroll() {
    this.fixedProductTitle()
    this.fixedTitle()
  },
  /** 判断是否滚动到了点评 */
  fixedTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#fixedTitle').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollClass: res[0] ? res[0].top < 1 + this.data.navigationHeight : true,
      })
    })
  },
  /** 判断是否滚动到了标题 */
  fixedProductTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#title').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollTop: res[0] ? res[0].top < this.data.navigationHeight - 5 : true,
      })
    })
  },
  getPosition() {
    const position = GlobalData.menuRect
    const { height, top, left } = position
    const marginLeft = left - 30
    const moreStyle = `top: ${top}px;height: ${height}px;left: ${marginLeft - 4}px;`
    this.setData!({
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
      navigationHeight: GlobalData.navigationHeight,
      moreStyle,
    })
  },
  onShareAppMessage() {
    this.setData({
      share: true,
    })
    return {
      path: $utils.getSharePath(),
    }
  },
  getUserId() {
    const user = wx.getStorageSync(`${getServer()}/logged`).data
    this.setData({
      isCreater: +this.data.activity.user_id === +user.id,
      mineId: user.id,
    })
    return user.id
  },
  /** 获取配置 */
  getBoot() {
    $event.on('after:boot', this, () => {
      this.setData({ access: GlobalData.access })
      this.getPosition()
    })
    this.setData({ access: GlobalData.access })
  },
  async getComment(id: number) {
    const comment = await activityApi.getActivityComments(id)
    this.setData({ comment })
  },
  async getDetail(id: number) {
    const activity = await activityApi.getActivity(id)
    activity.date = activity.date.replace('00:00:00', '')
    activity.content = activity.content.replace(/<p/gi, '<p class="richText" ')
    activity.content = activity.content.replace(/<img/gi, '<img class="quill-image" ')
    this.setData({
      activity,
      events: activity,
      isLoading: true,
    })
  },
  /** 对活动感兴趣 */
  async toInterest() {
    await checkAuth()

    if (this.data.activity.interested) {
      // 取消感兴趣
      await activityApi.deleteInsterestActivity(+this.data.activity.id)
      const interested = !this.data.activity.interested
      this.setData({
        [`activity.interested`]: interested,
        [`activity.interesteds_count`]: this.data.activity.interesteds_count - 1,
      })
      $event.emit('after:eventChange')
    } else {
      // 感兴趣
      await activityApi.insterestActivity(+this.data.activity.id)
      const interested = !this.data.activity.interested
      this.setData({
        [`activity.interested`]: interested,
        [`activity.interesteds_count`]: this.data.activity.interesteds_count + 1,
      })
      $event.emit('after:eventChange')
    }
  },
  /**想加入 */
  async toJoin() {
    await checkAuth()
    if (this.data.wantJoin || this.data.activity.wantJoin) {
      wx.showToast({
        title: '您已加入过了哟',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    this.setData({
      wantJoin: true,
    })
    await activityApi.wantJoinActivity(+this.data.activity.id)
    const wantJoin = !this.data.activity.wantJoin
    this.setData({
      [`activity.wantJoin`]: wantJoin,
      [`activity.want_joins_count`]: this.data.activity.want_joins_count + 1,
      wantJoin: false,
    })
    $event.emit('activityChange', this.data.activity)
    wx.showToast({
      title: '加入成功',
      icon: 'none',
      duration: 1000,
    })
    $event.emit('after:eventChange')
  },
  /** 写点评 */
  async publish() {
    await checkAuth()
    wx.showActionSheet({
      itemList: ['文字', '图片', '视频'],
      success(res) {
        switch (res.tapIndex) {
          case 0:
            wx.navigateTo({
              url: `/pages/publish/publish?about=events`,
            })
            break

          case 1:
            wx.navigateTo({
              url: `/pages/publish/publish?type=image&about=events`,
            })
            break
          case 2:
            wx.navigateTo({
              url: `/pages/publish/publish?type=video&about=events`,
            })
            break
        }
      },
    })
  },
  /** 操作 */
  async operation() {
    await checkAuth()

    const itemList: any[] = []

    if (this.data.isCreater) {
      itemList.push('编辑')
      itemList.push('删除')
    } else {
      itemList.push('举报')
    }

    wx.showActionSheet({
      itemList: itemList,
      success: (res) => {
        switch (itemList[res.tapIndex]) {
          case '编辑':
            wx.navigateTo({
              url: `/pages/activity/publish/publish?type=1`,
            })
            break
          case '删除':
            activityApi
              .DeleteActivity(this.data.id)
              .then((res) => {
                wx.showToast({
                  title: '删除成功',
                })
                setTimeout(() => {
                  wx.navigateBack({ delta: 1 })
                }, 1000)
              })
              .catch(() => {
                wx.showToast({
                  title: '删除失败',
                  icon: 'none',
                })
              })
            break
          case '举报':
            wx.navigateTo({
              url: `/pages/report/report?type=activity&id=${this.data.activity.id}`,
            })

            break
        }
      },
    })
  },
  /**
   * 查看发起人信息
   */
  viewUser() {
    wx.navigateTo({
      url: `/mine/homePage/homePage?id=${this.data.activity.user_id}`,
    })
  },
  /** 成员列表 */
  toMemberList() {
    wx.navigateTo({
      url: `/mine/activity-follower/activity-follower?id=${this.data.activity.id}`,
    })
  },
})
